package com.kienbk1910.productmanager;

import java.io.File;

import com.kienbk1910.common.Commom;
import com.kienbk1910.model.Product;
import com.kienbk1910.productmanager.provider.ProductProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewProductActivity extends Activity implements OnClickListener {
	private TextView etbarcode;
	private TextView extName;
	private TextView extManu;
	private TextView extCost;
	private TextView extCount;
	private TextView extNote;
	private ImageView photo;
	private Product product;
	private Button btnEdit;
	private Button btnDelete;
	private final static int EDIT_RESQUEST = 333;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_product);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setTitle("Xem thông tin sản phẩm");
		etbarcode = (TextView) findViewById(R.id.editBarcode);
		extName = (TextView) findViewById(R.id.etx_name);
		extManu = (TextView) findViewById(R.id.etx_manu);
		extCost = (TextView) findViewById(R.id.etx_cost);
		extCount = (TextView) findViewById(R.id.etx_count);
		extNote = (TextView) findViewById(R.id.etx_note);
		photo = (ImageView) findViewById(R.id.photo);
		btnEdit = (Button) findViewById(R.id.btn_edit);
		btnDelete = (Button) findViewById(R.id.btn_delete);

		product = (Product) getIntent().getSerializableExtra(Commom.PRODUCT);

		btnDelete.setOnClickListener(this);
		btnEdit.setOnClickListener(this);
		updateGui();

	}
     private void updateGui(){

 		extName.setText(product.getName());
 		extManu.setText(product.getManufacturer());
 		extCost.setText(Commom.intToStringWithplot(product.getCost()));
 		extCount.setText(String.valueOf(product.getCount()));
 		etbarcode.setText(product.getBarcode());
 		extNote.setText(product.getNote());
     }
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		if (product.getImagePath() != null
				&& product.getImagePath().length() > 0) {
			File imgFile = new File(product.getImagePath());
			if (imgFile.exists()) {

				int targetW = photo.getWidth();
				int targetH = photo.getHeight();
				Log.d("kienbk1910", "w:" + targetH + "h:" + targetW);
				Bitmap bitmap = decodeSampledBitmapFromResource(
						imgFile.getAbsolutePath(), targetW, targetH);
				photo.setImageBitmap(bitmap);

			}
		}
	}
  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	// TODO Auto-generated method stub
	super.onActivityResult(requestCode, resultCode, data);
	if(requestCode  == EDIT_RESQUEST && resultCode == RESULT_OK){
		product = (Product) data.getSerializableExtra(Commom.PRODUCT);
		updateGui();
		
	}
	Log.d("kienbk1910", "run result");
}
	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_product, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		} else if (id == android.R.id.home) {
			finish();
			overridePendingTransition(R.anim.slide_in_left,
					R.anim.slide_out_right);

		}
		return super.onOptionsItemSelected(item);
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			final int halfHeight = height / 2;
			final int halfWidth = width / 2;

			// Calculate the largest inSampleSize value that is a power of 2 and
			// keeps both
			// height and width larger than the requested height and width.
			while ((halfHeight / inSampleSize) > reqHeight
					&& (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}

		return inSampleSize;
	}

	public static Bitmap decodeSampledBitmapFromResource(String pathName,
			int reqWidth, int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(pathName, options);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_delete:
			new AlertDialog.Builder(this)
					.setTitle("Xác nhận")
					.setMessage(
							"Bạn có chắc chắn muốn xóa không, dư liệu sẽ mất vĩnh viễn?")
					.setPositiveButton("Đồng ý",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									// continue with delete
									deleteProduct(product);
								}
							})
					.setNegativeButton("Không",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									// do nothing
								}
							}).setIcon(android.R.drawable.ic_dialog_alert)
					.show();
			break;
		case R.id.btn_edit:
			Intent intent = new Intent(ViewProductActivity.this,
					AddProductActivity.class);
			intent.putExtra(Commom.PRODUCT, product);
			intent.putExtra(Commom.MODE, Commom.EDIT);
			startActivityForResult(intent, EDIT_RESQUEST);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		default:
			break;
		}

	}

	private void deleteProduct(Product product) {
		String URL = ProductProvider.URL + "/" + product.getId();
		Uri friends = Uri.parse(URL);
		int count = getContentResolver().delete(friends, null, null);
		if (product.getImagePath() != null
				&& product.getImagePath().length() > 0) {
			File file = new File(product.getImagePath());
			if (file.exists()) {
				boolean deleted = file.delete();
			}
		}
		Toast.makeText(this, "Bạn đã xóa một sản phẩm khỏi danh sách", Toast.LENGTH_LONG).show();
		finish();
		overridePendingTransition(R.anim.slide_in_left,
				R.anim.slide_out_right);

	}
}
